import React, { useState, useEffect, useRef } from 'react';
import Taro, { FC } from '@tarojs/taro';
import { combineLatest, EMPTY, firstValueFrom, interval, of, Subject, Subscription } from 'rxjs';
import { catchError, debounceTime, distinctUntilChanged, filter, mergeMap, switchMap, tap } from 'rxjs/operators';
import { PaginationResponse } from '@datorama/akita';
import { Button, Image, View, Label, Textarea, ScrollView, Text, ITouchEvent, Input, SwiperItem, Swiper } from '@tarojs/components';

import { getLogger } from '@/utils/log';
import { COMPONENT_OPERATION, HEARTBEAT_INTERVAL, INVITE_STATUS, LIVE_OPERATION, LIVE_TYPE, ROOMSTATS_TYPE, ROOM_ROLE, ROOM_STATUS } from '@/constants/room';
import { useRoomUiFacade } from '@/hooks/useRoomUiFacade';
import { useRoomDataFacade } from '@/hooks/useRoomDataFacade';
import { formatSeconds, formatTime, numFormat } from '@/utils';
import { useMsgFacade } from '@/hooks/useMsgFacade';
import { uploadFile } from '@/utils/qcloudHelpers';
import Login from '@/components/loginPopup';
import { useAuthFacade } from '@/hooks/useAuthFacade';
import { CMD } from '@/constants/message';
import { File, BeautyLevel, FileType } from '@/models/LiveRoom';
import { DeleteFileReq, FileSyncsType, ShareListReq, UploadFileReq } from '@/models/request/roomReq';
import { useAudiencesFacade } from '@/hooks/useAudiencesFacade'
import { AudienceItem } from '@/models/response/roomRsp';
import { LinkRequest } from '@/models/request/msgReq';

import { AtFloatLayout, AtGrid } from 'taro-ui';
import "taro-ui/dist/style/components/button.scss" // 按需引入  
import "taro-ui/dist/style/components/grid.scss";
import "taro-ui/dist/style/components/float-layout.scss";
import "taro-ui/dist/style/components/noticebar.scss";
import "taro-ui/dist/style/components/modal.scss";

import ChannelSytle from '@@/channel/channelStyle'
import './index.scss';

//定义组件入参
type Props = {
  //房间Id
  roomId: string;
}

//直播未开始
export const Index: FC<Props> = ({ roomId }) => {
  const logger = getLogger("/components/LiveOperation");

  const initSubject = () => new Subject<any>();
  const [emitter, setEmitter] = useState(initSubject);

  const [authFacade, loginStatus, userId, , , userInfo] = useAuthFacade();
  const [, , , type] = useRoomDataFacade();

  const [msgFacade, msgList, , , , ,] = useMsgFacade();

  //触发登录跳转的地址
  const [hasSignIn, setHasSignIn] = useState(false);

  //消息数， 用于显示新消息logo
  const msgCountRef = useRef(msgList.length);

  //导入门面的所有元素作为页面绑定
  const [
    roomFacade,
    roomName,
    anchorId,
    anchorName,
    ownerName,
    ownerId,
    ownerLogo,
    anchorLogo,
    orgId,
    roomRole,
    orgName,
    orgLogo,
    tip,
    roomStatus,
    files,
    description,
    startTime,
    endTime,
    duration,
    visits,
    shares,
    likes,
    ,
    picUrl,
    forceSignIn,
    allowShare,
    liveStreams,
    ,
    ui_progress,
    ui_videoEnded,
    audioStatus,
    audienceToast
  ] = useRoomUiFacade();

  const [audiencesFacade, pagination] = useAudiencesFacade(roomId);

  //登录弹窗相关状态
  const [clicked, setClicked] = useState(false);
  const [goUrl, setGoUrl] = useState('');
  const [openSetting, setOpenSetting] = useState(false);   //主播设置弹框
  const [isOpenFile, setOpenFile] = useState(false); //文件上传弹框
  const [isPlaying, setIsPlaying] = useState(false);   //开始播放视频
  const [inputVal, setInputVal] = useState(""); //输入文本内容
  const [keyboardHeight, setKeyboardHeight] = useState(0) //输入法键盘高度
  const [showInput, setShowInput] = useState(false)//显示/隐藏输入文本框
  const [showModel, setShowModel] = useState(false)//开播提示
  const [isOpenTop, setOpenTop] = useState(false);  //简介信息隐藏/显示
  const [showDetele, setShowDetele] = useState(false)//删除文件提示
  const [filesId, setFilesId] = useState('')//文件Id
  const [like, setLike] = useState(false) //点赞判断
  const [timeShow, setTimeShow] = useState(false) //显示/隐藏倒计时10秒
  const [timeValue, setTimeValue] = useState(10) //开始倒计时10秒 
  const refDuration = useRef(duration);//时长缓存
  const [timeData, setTimeData] = useState(''); //主播计时器
  const [toview, setToview] = useState(''); //消息区域滚动位置
  const [endLive, setEndLive] = useState(false)//结束直播提示  
  const [hasNewMsg, setHasNewMsg] = useState(false);//是否有新消息
  const autoScrollRef = useRef(true)//留言区是否自动滚动
  const [navBarHeight, setNavBarHeight] = useState(0);//导航栏高度
  const [navHeight, setNavHeight] = useState(0);//胶囊高度
  const [topPadding, setTopPadding] = useState(0);//胶囊上边距
  const [navWidth, setNavWidth] = useState(0);//胶囊宽度 
  const [statusBarHeight, setstatusBarHeight] = useState(0);//状态栏高度 
  const [topMargin, setTopMargin] = useState(0);//高度差
  const [screenWidth, setScreenWidth] = useState(0);//屏幕宽度
  const [screenHeight, setScreenHeight] = useState(0);//屏幕高度
  const [isclick, setIsclick] = useState(false);//是否点击了观看回放
  const [isclickMouse, setIsclickMouse] = useState(false);//点击隐藏按钮
  const [isHorizontal, setIsHorizontal] = useState(false) //判断是否为横屏
  const [isAttention, setIsAttention] = useState(false)  //是否关注了
  const [openShare, setOpenShare] = useState(false)  //显示、隐藏分享榜单
  const [isInvite, setIsInvite] = useState(false) // 显示邀请连线列表
  const [searchKey, setSearchKey] = useState('-1') // 搜索连麦字段
  const [audienceList, setAudienceList] = useState([] as AudienceItem[]) // 连麦列表
  const [shareData, setShareData] = useState([] as ShareListReq[]);
  const [filesIndex, setFilesIndex] = useState(0) // 文件索引值
  const [showFiles, setShowFiles] = useState(false) // 是否显示演示文件框
  const [currentValue, setCurrentValue] = useState(-1) // 文件演示页面切换值
  const [isSucceed, setIsSucceed] = useState(false) // 文件转码状态
  const [filesArry, setFilesArry] = useState([] as FileType[]) // 新的文件数组 
  const [isWatch, setIsWatch] = useState(false) // 是否观看文件演示
  const dynamicRef = useRef(false)//文件是否是动态ppt 
  const [isAcceptInvite, setIsAcceptInvite] = useState(false) // 是否确认连麦邀请 
  const [inviteState, setInviteState] = useState(-2) // 邀请连麦的状态
  const [inviteIndex, setInviteIndex] = useState(0) // 邀请连麦对象的索引
  const [fileSynUrl, setFileSynUrl] = useState('') // 同步演示的图片地址
  const [totalPages, setTotalPages] = useState(0) // 同步演示文件总页数
  const [filePage, setFilePage] = useState(1) // 翻页页码
  const [fileSynData, setFileSynData] = useState([] as FileSyncsType[]); //拉取回放文件翻页记录数据 
  const [playedShow, setPlayedShow] = useState(false) // 回放演示框显示/隐藏
  const [playedIcon, setPlayedIcon] = useState(false) // 回放演示图标显示/隐藏
  const [singleFile, setSingleFile] = useState({} as FileSyncsType) // 单个文件记录数据

  //图片后缀
  const img = currentValue + 1 + ".jpg"

  //设置弹框的数据
  const AtGridData = [
    {
      image: 'https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/edit.png',
      value: '编辑房间'
    },
    {
      image: 'https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/share1.png',
      value: '允许分享'
    },
    {
      image: 'https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/setPwd.png',
      value: '密码设置'
    },
    {
      image: 'https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/sigining.png',
      value: '签到设置'
    },
    {
      image: 'https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/Team.png',
      value: '团队管理',
    },
    {
      image: 'https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/comments.png',
      value: '评论设置'
    },
    {
      image: 'https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/paushed.png',
      value: '暂停直播'
    }
  ]

  //直播未开始的数组数据处理
  const dataArr = [...AtGridData].filter(({ value }) => value !== "暂停直播")
  //直播中的数组数据
  const data1Arr = [...AtGridData].filter(({ value }) => value !== "编辑房间")
  //直播结束后的数组数据
  const data2Arr = [...AtGridData].filter(({ value }) => value == "允许分享" || value === "密码设置" || value === "评论设置")

  //隐藏/显示主播设置弹框
  const setting = (e: ITouchEvent) => {
    e.stopPropagation();
    setOpenSetting(true)
  }

  //隐藏/显示上传文件弹框
  const openFileMenu = (e: ITouchEvent) => {
    e.stopPropagation()
    setOpenFile(true)
  }

  //点击隐藏按钮
  const clickShow = () => {
    setIsclickMouse(!isclickMouse)
  }

  //隐藏上传文件弹框
  const closeAllPop = (e: ITouchEvent) => {
    console.log("全体弹窗重置")
    e.stopPropagation()
    setOpenFile(false);
    setOpenSetting(false);
    setOpenTop(false);
    setShowModel(false);
    setEndLive(false);
    setOpenShare(false)
    setIsInvite(false)
  }

  //隐藏/显示开始直播提示框
  const setShow = (e: ITouchEvent) => {
    e.stopPropagation()
    if (roomStatus === ROOM_STATUS.PAUSED) {
      resumePush();
    } else {
      setShowModel(true)
    }
  }

  //隐藏/显示结束直播提示框
  const setEndShow = (e: ITouchEvent) => {
    e.stopPropagation()
    setEndLive(true)
  }

  //简介信息隐藏/显示
  const handleClick = (e: ITouchEvent) => {
    e.stopPropagation()
    setOpenTop(true)
  }

  //是否点击了关注
  const isClickAttention = () => {
    setIsAttention(!isAttention)
    if (orgId == '') {
      authFacade.addFollow((anchorId || ownerId), null as any, !isAttention)
    } else {
      authFacade.addFollow(null as any, orgId, !isAttention)
    }
  }

  //分享榜排序 
  const bubbleSort = (arr) => {
    const len = arr.length;
    for (let i = 0; i < len; i++) {
      for (let j = 0; j < len - 1 - i; j++) {
        if (arr[i].counts > arr[j + 1].counts) { //相邻元素两两对比
          const temp = arr[j + 1]; //元素交换
          arr[j + 1] = arr[j];
          arr[j] = temp;
        }
      }
    }
    setShareData(arr)
    return arr;
  }

  //显示分享榜单弹窗
  const clickOpenShare = async (e: ITouchEvent) => {
    e.stopPropagation()
    setOpenShare(true)
    const res = await firstValueFrom(roomFacade.getRefRanking(roomId))
    // bubbleSort(res)
    try {
      setShareData(res)
      console.log('获取分享数据成功: ', res)
    } catch (error) {
      console.error("调用错误: ", error)
    }
  }

  //隐藏/显示文件删除提示框
  const cancelDeteleFiles = (index) => {
    setShowDetele(!showDetele)
    setFilesIndex(index)
  }

  //键盘弹起高度设置
  const getKeyboardHeight = (e) => {
    setKeyboardHeight(e.mpEvent.detail.height)
  }

  const onKeyboardheightchange = (e) => {
    Taro.onKeyboardHeightChange(res => {
      setKeyboardHeight(res.height)
    })
  }

  //隐藏输入框
  const hideInput = () => {
    //触发登录弹窗
    setClicked(true);
    //需要再登录成功后重新点击一次
    if (loginStatus === true) {
      console.log("输入法打开")
      setShowInput(!showInput)
    }
  }

  //观众是否观看文件演示
  const clickWatch = () => {
    setIsWatch(!isWatch)
  }

  //回放中是否观看文件演示
  const clickPlayed = () => {
    setPlayedShow(!playedShow)
  }

  // 上传文件
  const clickUploadFile = () => {
    Taro.chooseMessageFile({
      count: 1,
      type: 'file',
      success(res) {
        uploadFile(res.tempFiles[0].path,
          (resUrl: string) => {
            const fileUrl = resUrl;
            const fileName = res.tempFiles[0].name;
            emitter.next({ roomId, fileName, fileUrl, action: "upload" });
          },
        )
      },
      fail(err) {
        console.log('文件上传失败:', err)
      }
    })
  }

  //打开文件查看
  const openFile = (fileUrl) => {
    Taro.downloadFile({
      url: fileUrl,
      success: function (res) {
        const filePath = res.tempFilePath
        Taro.openDocument({
          filePath: filePath,
          success: function () {
            console.log('打开文档成功')
          }
        })
      }
    })
  }

  //TODO 删除文件
  const deleteFile = (index) => {
    setShowDetele(!showDetele)
    const file = files[index];
    const fileId = file.id;
    emitter.next({ roomId, fileId, action: "delete" });
  }

  //演示文件按钮以及文件转码请求操作
  const fileTransCode = (id, fileUrl, index1) => {
    const file = files[index1];
    const pages = file.pages as number
    const transcodeUrl = file.transcodeUrl as string
    const page = 1 as number
    const imgs = "1.jpg"
    checkStr(transcodeUrl)
    setFilesIndex(index1)
    if (pages == 0 && transcodeUrl == undefined) {
      //发起文件转码请求
      roomFacade.fileTransCode({ roomId, id, fileUrl })
      setIsSucceed(true)
      setCurrentValue(0)
    } else if (dynamicRef.current) {
      Taro.showToast({
        title: '文件中含有动态效果请去除再上传',
        icon: 'none',
        duration: 3000
      })
    } else {
      setShowFiles(true)
      setCurrentValue(0)
      setIsSucceed(false)
      setFileSynUrl(transcodeUrl + imgs)
      roomFacade.fileSyn({ roomId, id, transcodeUrl, page, pages })
    }
  }

  //判断转码的文件是否是动态的html
  const checkStr = (str) => {
    const myReg = /\.(html)$/;
    if (myReg.test(str)) {
      dynamicRef.current = true;
    } else {
      dynamicRef.current = false
    }
  }

  //主播端文件演示返回操作
  const back = (e) => {
    e.stopPropagation()
    setShowFiles(false)
    setOpenFile(true)
    setFilesArry([])
    setCurrentValue(-1)
    setFileSynUrl('')
    roomFacade.syncEnded(roomId)
  }

  //观众端返回操作
  const toBack = (e) => {
    e.stopPropagation()
    setIsWatch(false)
    setTotalPages(0)
  }

  //切换ppt页面
  const SelectOptions = (e) => {
    const current = e.detail.current
    setCurrentValue(current)
  }

  //点击上一页
  const clickPrev = (index) => {
    const current = currentValue - 1;
    const file = files[index];
    const id = file.id
    const page = currentValue
    const pages = file.pages as number
    const transcodeUrl = file.transcodeUrl as string
    if (current < 0) {
      Taro.showToast({
        title: '已经是第一张了',
        icon: 'none',
        duration: 3000
      })
    } else {
      setCurrentValue(current)
      roomFacade.fileSyn({ roomId, id, transcodeUrl, page, pages })
    }
  }

  //点击下一页
  const clickNext = (index) => {
    const current = currentValue + 1;
    const pageValue = currentValue + 2;
    const file = files[index];
    const pages = file.pages as number
    const id = file.id
    const transcodeUrl = file.transcodeUrl as string
    const page = pageValue as number
    if (current >= pages) {
      Taro.showToast({
        title: '已经是最后一张了',
        icon: 'none',
        duration: 3000
      })
    } else {
      setCurrentValue(current)
      roomFacade.fileSyn({ roomId, id, transcodeUrl, page, pages })
    }
  }

  //接收用户操作按钮等事件传入数据
  useEffect(() => {
    const subscriptions: Subscription[] = [
      emitter.asObservable()
        .pipe(
          switchMap(req => {
            if (req.action === "upload") {
              const params = {} as UploadFileReq;
              params.fileName = req.fileName;
              params.fileUrl = req.fileUrl;
              params.roomId = req.roomId;
              return roomFacade.uploadFile(params);
            } else {
              const params = {} as DeleteFileReq;
              params.roomId = req.roomId;
              params.fileId = req.fileId;
              return roomFacade.deleteFile(params);
            }
          }),
        )
        .subscribe({
          next: console.log,
          error: () => setEmitter(initSubject)
        }),
    ]
    return () => { subscriptions.map(sub => sub.unsubscribe()) };
  }, [emitter])

  //点赞操作
  const clickLike = () => {
    setClicked(true);
    setLike(true)
    setTimeout(() => {
      setLike(false)
    }, 1000);

    const likeUserId = anchorId ? anchorId : ownerId; //被点赞的主播Id;
    firstValueFrom(roomFacade.saveRoomStat(roomId, ROOMSTATS_TYPE.LIKED));
    firstValueFrom(roomFacade.updateEtcData(roomId, { anchorId: likeUserId, likes: 5 }));
  }

  //签到操作
  const signIn = () => {
    // setGoUrl(`/pages/liveRoom/signIn/index?roomId=${roomId}&liveType=${LIVE_TYPE.AUDIO}`);
    setGoUrl(`/subPages/liveRoom/signIn/index?roomId=${roomId}&liveType=${LIVE_TYPE.AUDIO}`);
    setClicked(true);
  }

  //开始直播倒计时 
  function daojishi() {
    setTimeShow(!timeShow);
    setShowModel(false);
    let time = 10;  //倒计时10秒开始
    const interval1 = setInterval(function () {
      time -= 1;
      setTimeValue(time)
      if (time == 0) {
        clearInterval(interval1);
        setTimeShow(false);
        startPush();
      }
    }, 1000)
  }

  // 取得右上角胶囊高度，自定义标题与其对齐  
  useEffect(() => {
    Taro.getSystemInfo({
      success: function (res) {
        let myStatusBar = 0     // 状态栏高度
        let myCustomBar = 0  //导航栏高度
        let myNvaMartom = 0  //高度差
        let myNavHeight = 0   //胶囊高度
        let myNavWidth = 0   //胶囊宽度
        let myTopPadding = 0   //胶囊上边距
        let myScreenWidth = 0  //屏幕宽度
        let myScreenHeight = 0  //屏幕高度
        const custom = Taro.getMenuButtonBoundingClientRect();
        myStatusBar = res.statusBarHeight || 0;
        myNavHeight = custom.height
        myNavWidth = custom.width
        myTopPadding = custom.top
        myNvaMartom = custom.top - myStatusBar;
        myCustomBar = (myNvaMartom * 2 + custom.height)
        myScreenWidth = res.screenWidth
        myScreenHeight = res.screenHeight
        if (isHorizontal == false) {
          setNavBarHeight(myCustomBar)
          setNavHeight(myNavHeight)
          setstatusBarHeight(myStatusBar)
          setTopMargin(myNvaMartom)
        } else {
          setTopPadding(myTopPadding)
        }
        setScreenWidth(myScreenWidth)
        setNavWidth(myNavWidth)
        setScreenHeight(myScreenHeight)
      }
    })
  }, [navBarHeight, screenWidth, navWidth, isHorizontal])

  // 转发直播间
  const shareRoom = () => {
    const nameParam = encodeURIComponent(roomName);
    const picParam = encodeURIComponent(picUrl);
    const timeParam = encodeURIComponent(formatTime(startTime));
    //TODO: 未开启分享时做何判断，图片是否为空，房间名称是否需要URIEncode
    // setGoUrl(`/pages/liveRoom/share/index?roomId=${roomId}&roomName=${nameParam}&picUrl=${picParam}&startTime=${timeParam}`);
    setGoUrl(`/subPages/liveRoom/share/index?roomId=${roomId}&roomName=${nameParam}&picUrl=${picParam}&startTime=${timeParam}`);
    setClicked(true);
  }

  //返回上一页
  const goBack = () => {
    Taro.navigateBack({
      delta: 1
    })
  }

  //返回首页
  const goHome = () => {
    Taro.switchTab({
      url: '/pages/index/index'
    })
  }

  //查看主播信息
  const goInformationPage = () => {
    Taro.navigateTo({
      url: `/subPages/my/userInformation/index?userId=${ownerId}&userAvar=${anchorLogo || ownerLogo}&isFollowed=${isAttention}`
    })
  }

  const goOrgInfoPage = () => {
    Taro.navigateTo({
      url: `/subPages/my/orgInformation/index?orgId=${orgId}&orgAvar=${anchorLogo || ownerLogo}&isFollowed=${isAttention}`

    })
  }

  //跳转页面
  const toTeam = (item, index: number) => {
    //阻止事件冒泡
    // event.stopPropagation(); 
    setClicked(true);

    if (item.value == '编辑房间') {
      // setGoUrl('/pages/liveRoom/editLive/index?roomId=' + roomId);
      setGoUrl('/subPages/liveRoom/editLive/index?roomId=' + roomId);
    }
    if (item.value == '允许分享') {
      // setGoUrl('/pages/liveRoom/allowShare/index?roomId=' + roomId);
      setGoUrl('/subPages/liveRoom/allowShare/index?roomId=' + roomId);
    }
    if (item.value == '密码设置') {
      // setGoUrl('/pages/liveRoom/pwdSetting/index?roomId=' + roomId);
      setGoUrl('/subPages/liveRoom/pwdSetting/index?roomId=' + roomId);
    }
    if (item.value == '签到设置') {
      // setGoUrl(`/pages/liveRoom/signInSetting/index?roomId=${roomId}&liveType=${LIVE_TYPE.AUDIO}`);
      setGoUrl(`/subPages/liveRoom/signInSetting/index?roomId=${roomId}&liveType=${LIVE_TYPE.AUDIO}`);
    }
    if (item.value == '团队管理') {
      // setGoUrl('/pages/liveRoom/TeamManagement/index?roomId=' + roomId);
      setGoUrl('/subPages/liveRoom/TeamManagement/index?roomId=' + roomId);
    }
    if (item.value == '评论设置') {
      // setGoUrl('/pages/liveRoom/chatSettings/index');
      setGoUrl('/subPages/liveRoom/chatSettings/index');
    }
    if (item.value == '暂停直播') {
      pausePush()
      setOpenSetting(false)
    }
  }

  //跳转评论页面
  const toChat = () => {
    setClicked(true);
    // setGoUrl('/pages/liveRoom/chat/index?roomId=' + roomId);
    setGoUrl('/subPages/liveRoom/chat/index?roomId=' + roomId);
  }

  //切换主播或者观众自己的静音状态
  const switchMute = () => {
    roomFacade.uiOperate(COMPONENT_OPERATION.TOGGLE_MUTE);
  }

  //添加更多其他按钮的操作
  const interaction = (item, index, e: ITouchEvent) => {
    if (item.value === '镜头切换') {
      //切换摄像头
      roomFacade.uiOperate(COMPONENT_OPERATION.TOGGLE_CAMERA);
    }
    if (item.value === '邀请连麦') {
      inviteContent(e)
    }
  }

  const switchCamera = () => {
    //切换摄像头
    roomFacade.uiOperate(COMPONENT_OPERATION.TOGGLE_CAMERA);
  }

  // 点击设置-邀请连麦按钮
  const inviteContent = async (e: ITouchEvent) => {
    e.stopPropagation()
    setIsInvite(true)
    setOpenSetting(false);
    // console.log('当前连麦人数', audienceToast);

    try {
      const res = await firstValueFrom(roomFacade.getSearchList(roomId, 1, 10, ''))
      setAudienceList(res.data as AudienceItem[])
    } catch (err) {
      console.error(err)
    }
  }

  // TODO 点击用户-邀请连麦
  const hanldeConnect = (userId2, index) => {
    // 点击后状态改为连麦中
    setInviteIndex(index)
    // if(inviteState !== INVITE_STATUS.ACCEPT && inviteState !== INVITE_STATUS.CONNECTING && audienceToast < 3) {
    msgFacade.sendLinkMsg(userId2, CMD.REQUEST_LINK)
    // }
  }

  // 返回设置弹窗
  const goBackSetting = (e) => {
    e.stopPropagation()
    setIsInvite(false)
    setOpenSetting(true);
  }

  // 邀请连麦弹窗
  const inviteModel = (e) => {
    e.stopPropagation()

  }

  // 连麦输入框
  const updateSearchInvite = (e) => {
    // 更新入参
    setSearchKey(e.detail.value)
    audiencesFacade.updateUI(e.detail.value)
  }
  // 点击搜索连麦按钮
  const searchInvite = () => {
    console.log('点击搜索');
    audiencesFacade.doSearch()
    // setAudienceList(pagination.data as AudienceItem[])
  }

  // 更新连麦邀请状态
  const updateInviteState = (status) => {
    // console.log('点击了链接', audienceList[index].inviteStatus);
  }

  const refreshAudienceList = () => {
    // 下一页数据
    audiencesFacade.nextPage()
  }

  //切换美颜等级
  const changeBeauty = (lv: BeautyLevel) => {
    roomFacade.uiOperate(COMPONENT_OPERATION.CHANGE_BEAUTY, lv.toString());
  }

  //观看回放
  const playBack = async () => {
    setIsclick(true)
    if (!liveStreams[0].videoUrl) {
      Taro.showToast({
        title: '回放生成中，请稍候...',
        icon: 'none',
        duration: 3000
      })
    } else {
      setIsPlaying(true);
      roomFacade.uiOperate(COMPONENT_OPERATION.PLAY_VIDEO);
      const res = await firstValueFrom(roomFacade.getFileSyncs(roomId))
      setFileSynData(res)
    }
  }

  //开始直播
  const startPush = () => {
    roomFacade.uiOperate(LIVE_OPERATION.START);
    setShowModel(!showModel)
  }

  //结束直播直播
  const endPush = () => {
    roomFacade.uiOperate(LIVE_OPERATION.STOP);
  }

  //暂停直播
  const pausePush = () => {
    //切换摄像头
    roomFacade.uiOperate(LIVE_OPERATION.PAUSE);
  }

  //恢复直播
  const resumePush = () => {
    //切换摄像头
    roomFacade.uiOperate(LIVE_OPERATION.RESUME);
  }

  const getInputVal = (e: any) => {
    const text = e.detail.value;
    setInputVal(text);
  }

  //发送聊天信息
  const sendRoomMsg = () => {
    const msg = inputVal.replace(/(^\s*)|(\s*$)/g, "");

    if (msg.length === 0) {
      Taro.showToast({
        title: '不能输入空文本...',
        icon: 'none',
        duration: 3000
      })
      return;
    }

    msgFacade.sendRoomTextMsg(msg)
      .then((res: any) => {
        //发送成功后清空输入框
        setInputVal("");
      })
    enableAutoScroll();
  }

  //开启留言区自动滚动并隐藏新消息logo
  const enableAutoScroll = () => {
    // setHasNewMsg(false);
    autoScrollRef.current = true;
    //自动滚动到最新
    setToview(`msg${msgList.length - 1}`);
  }

  //取消留言区自动滚动
  const disableAutoScroll = (e) => {
    autoScrollRef.current = false;
  }

  const msgEffect = () => {
    const sub = msgFacade.msgList$
      .pipe(
        filter(list => list && list.length > 0),
        tap(list => {
          if (!autoScrollRef.current && list.length > msgCountRef.current) {
            //非自动滚动状态下有新消息才会出现新消息logo
            setHasNewMsg(true);
            setToview('');
          } else {
            //写入最新消息长度
            msgCountRef.current = list.length;
            setHasNewMsg(false);
            //自动滚动到最新
            setToview(`msg${list.length - 1}`);
          }
        })
      )
      .subscribe()

    return sub;
  }

  //接收消息的滚动
  useEffect(() => {
    const sub = msgEffect()
    return () => sub.unsubscribe();
  }, [])

  const timeEffect = () => {
    setTimeData(formatSeconds(refDuration.current));
  }

  //刚进入房间时的直播时长显示
  useEffect(() => {
    if (duration > 0) {
      refDuration.current = duration;
      timeEffect();
    }

  }, [duration])

  //主播计时器
  useEffect(() => {
    let counter: NodeJS.Timer;
    if (roomStatus === ROOM_STATUS.STARTED) {
      counter = setInterval(() => {
        refDuration.current += 1;
        timeEffect();
      }, 1000)
    }

    return () => {
      //FIXME 此处逻辑不可靠，数据不准确
      if (refDuration.current > 0 && (roomRole === ROOM_ROLE.ANCHOR || roomRole === ROOM_ROLE.OWNER_ANCHOR)) {
        //更新本地最新直播时长
        firstValueFrom(roomFacade.updateEtcData(roomId, { duration: refDuration.current }));
      }
      counter && clearInterval(counter);
    }
  }, [roomStatus, roomRole])

  //提取副作用到独立函数
  const onceEffect = () => {
    const subs = [
      //如果在直播间触发了登录弹窗，则重新加群
      combineLatest([authFacade.loginStatus$, msgFacade.isSDKReady$])
        .pipe(
          debounceTime(500),
          //auth store刷新后才需要重新登录IM
          filter(([isLogin, isSDKReady]) => isLogin && isSDKReady),
          //加群
          tap(() => msgFacade.applyJoinBigGroup(roomId)),
          //TODO: 减少请求 获取签到内容
          mergeMap(res => roomFacade.signInOptions$),
          tap(res => {
            if (res && res.length > 0) {
              //异步拉回来签到内容再开启签到按钮
              setHasSignIn(true);
            } else {
              setHasSignIn(false);
            }
          }),
          //switchMap(() => roomFacade.getInvites(roomId))
        )
        //重新登录后必须重新计算身份
        .subscribe(),

      //处理系统群发通知
      roomFacade.handleGroupSystemNotify$
        .pipe(
          tap(msg => {
            // console.warn("liveOperator群发通知消息收到时间：", new Date().getTime());
            msgFacade.clearNotifyMsg();
            //不在上一个tap内运行是考虑store更新的异步延迟问题，在本周期内才能获取最新数据
            switch (msg.cmd) {
              case CMD.ADD_INVITE_ANCHOR:
              case CMD.ADD_ASSISTANT:
              case CMD.DEL_INVITE_ANCHOR:
              case CMD.DEL_ASSISTANT:
                {
                  roomFacade.judgeRole();
                  break;
                }
              case CMD.KICK_MEMBER:
                {
                  Taro.showToast({
                    title: '你已被踢出直播间',
                    icon: 'none',
                    duration: 2000
                  })
                  //C2C消息，只有被踢的人接收到，需要结合黑名单进行使用
                  setTimeout(() => {
                    Taro.switchTab({
                      url: `/pages/my/index/index`
                    })
                  }, 2000)
                  break;
                }
              case CMD.CHANGE_TIPS:
                {
                  console.error("修改群提示通知：", msg.data)
                  const data = msg.data;
                  //插入新的群提示消息
                  msgFacade.insertTips(roomId, data.tips);
                  break;
                }
              case CMD.TRANSCODE_FILES:
                {
                  console.error("文件转码通知：", msg.data)
                  //转码成功重新获取文件列表
                  const data = msg.data;
                  const pages = data.file.pages
                  const transcodeUrl = data.file.transcodeUrl
                  const id = data.file.id
                  const page = 1 as number
                  const imgs = "1.jpg"
                  checkStr(transcodeUrl)
                  if (dynamicRef.current) {
                    Taro.showToast({
                      title: '文件中含有动态效果请去除再上传',
                      icon: 'none',
                      duration: 3000
                    })
                  } else {
                    setShowFiles(true)
                    setCurrentValue(0)
                    setTotalPages(pages)
                    // roomFacade.getFiles(roomId)
                    setFileSynUrl(transcodeUrl + imgs)
                    roomFacade.fileSyn({ roomId, id, transcodeUrl, page, pages })
                  }
                  setIsSucceed(false)
                  break;
                }
              case CMD.SYNC_PAGE:  //文件翻页通知
                {
                  // console.log("文件翻页通知：", msg.data)
                  const data = msg.data;
                  const url = data.transcodeUrl as string;
                  const page = data.page as number;
                  const pages = data.pages as number;
                  const pageUrl = url + page + ".jpg";
                  setFileSynUrl(pageUrl)
                  setFilePage(page)
                  setTotalPages(pages)
                  setShowFiles(true)
                  //TODO 翻页同步处理逻辑
                  break;
                }
              case CMD.SYNC_ENDED:
                {
                  // console.log("文件演示结束通知：", msg.data)
                  setShowFiles(false)

                  //TODO  文件演示结束处理逻辑
                  break;
                }
              case CMD.FORCE_SIGN_IN:
                {
                  //在房间收到签到通知，实时开启签到按钮
                  const data = msg.data;
                  if (data.hasSignInContent) {
                    setHasSignIn(true);
                  } else {
                    setHasSignIn(false);
                  }
                  break;
                }
              case CMD.REQUEST_LINK:
                {
                  // const data = JSON.parse(msg.data) as LinkRequest;
                  const data = msg.data as LinkRequest;
                  console.error('传参是何值', data);
                  setInviteState(INVITE_STATUS.CONNECTING)
                  Taro.showModal({
                    content: '主播对你发出了连线邀请',
                    cancelText: "拒绝",
                    confirmText: '接受',
                    success: async (res) => {
                      if (res.confirm) {
                        try {
                          await firstValueFrom(roomFacade.accessAudienceInvite(roomId))
                          console.log('用户点击了确定, 接受邀请')
                          //通知大主播对方已接受，并获取新的连麦流
                          msgFacade.sendLinkMsg(data.from, CMD.ACCEPT_LINK)
                        } catch (err) {
                          console.error(err);
                        }
                      } else if (res.cancel) {
                        msgFacade.sendLinkMsg(data.from, CMD.REFUSE_LINK)
                      }
                    }
                  })
                  break;
                }
              case CMD.ACCEPT_LINK:
                {
                  Taro.showToast({
                    title: '已接通',
                    icon: 'none',
                    duration: 2000
                  })

                  setInviteState(INVITE_STATUS.ACCEPT)
                  break;
                }
              case CMD.REFUSE_LINK: {
                Taro.showToast({
                  title: '对方已拒绝',
                  icon: 'none',
                  duration: 2000
                })
                setInviteState(INVITE_STATUS.REFUSE)
                break;
              }
              default:
                break;
            }
          }),
          catchError(err => {
            logger.ERROR("发生异常错误：", err);
            return of(true);
          })
        )
        .subscribe(),

      //心跳请求，未登录也可以返回数据
      interval(HEARTBEAT_INTERVAL)
        .pipe(
          switchMap(() => roomFacade.updateTS(roomId)),
        )
        .subscribe(),

      //查询关注状态
      combineLatest([authFacade.loginStatus$, roomFacade.orgId$, roomFacade.ownerId$, roomFacade.anchorId$])
        .pipe(
          //未登录用户不需要查询关注状态
          filter(([this_login]) => this_login),
          switchMap(([this_login, this_org, this_owner, this_anchor]) => authFacade.isFollowed((this_anchor || this_owner), this_org)),
          tap(res => setIsAttention(res.data))
        )
        .subscribe(),

      //获取订阅权限
      roomFacade.roomRole$
        .pipe(
          filter(role => role === ROOM_ROLE.ANCHOR || role === ROOM_ROLE.OWNER_ANCHOR || role === ROOM_ROLE.OWNER_ASSISTANT || role === ROOM_ROLE.ASSISTANT),
          switchMap(authFacade.getSubs)
        )
        .subscribe(),

      //房间类型是OBS
      roomFacade.type$
        .pipe(
          tap(this_type => {
            // 录播状态下不需要开播按钮
            if (this_type === LIVE_TYPE.OBS_REC) {
              roomFacade.uiOperate(LIVE_OPERATION.START);
            }
          })
        )
        .subscribe(),
    ]
    return subs;
  }

  //state状态处理总入口
  useEffect(() => {
    const subscriptions: Subscription[] = onceEffect();

    return () => { subscriptions.map(sub => sub.unsubscribe()) };
  }, [])

  //提取set状态的操作到外部函数
  const changeFilesEffect = (val: number, fileArr: File[]) => {
    if (val !== -1) {
      const file = fileArr[filesIndex];
      const fileId = file.id
      const page = file.pages as number
      const transcodeUrl = file.transcodeUrl
      const imgArry = Array.from(Array(page)).map((item, index) => ({ fileId: fileId, transcodeImgUrl: transcodeUrl + img, pages: page }))
      setFilesArry(imgArry)
    }
  }

  useEffect(() => {
    changeFilesEffect(currentValue, files);
  }, [currentValue, files])

  const horiEffect = (isHori: boolean) => {
    Taro.onWindowResize((res) => {
      if (res.size.windowWidth > res.size.windowHeight) {
        setIsHorizontal(true)
      } else {
        setIsHorizontal(false)
      }
    })
  }

  //监听手机屏幕的宽度变化，横竖屏切换
  useEffect(() => {
    horiEffect(isHorizontal);

  }, [isHorizontal])

  const audListEffect = (pageData: PaginationResponse<Record<string, any>>) => {
    // 输入框有值的时候直接顶替， 没值的时候拼接
    if (!!searchKey && pageData.data && pageData.data.length === 0 && pageData.currentPage === 1) {
      setAudienceList([])
    }
    if (pageData.data && pageData.data.length > 0) {
      if (pageData.currentPage > 1) {
        // console.log('现在触发页数大于1', audienceList);

        setAudienceList(audienceList.concat(pageData.data as AudienceItem[]))
      } else {
        setAudienceList(pageData.data as AudienceItem[])
      }
    }
  }

  // 监听连麦列表
  useEffect(() => {
    audListEffect(pagination);
  }, [pagination])

  // // 输入框更改时就查询
  // useEffect(() => {
  //   // 页面渲染时不触发
  //   console.log('searchKeyd zhi ', searchKey);

  //   if (searchKey !== '-1') {
  //     audiencesFacade.doSearch()
  //   }
  // }, [searchKey])

  const updateAudListEffect = (status: number) => {
    if (status !== -2 && !!audienceList && audienceList.length > 0) {
      console.log('更新状态没有111');

      audienceList[inviteIndex].inviteStatus = status;
      setAudienceList(JSON.parse(JSON.stringify(audienceList)))
    }
  }

  // 根据连麦状态更新列表
  useEffect(() => {
    updateAudListEffect(inviteState);
  }, [inviteState, pagination])

  // 根据当前回放播放进度渲染文件演示记录
  const filePlayEffect = (playing: boolean, syncData: FileSyncsType[]) => {
    return roomFacade.videoProgress$
      .pipe(
        filter(() => playing),
        distinctUntilChanged(),
        mergeMap(progress => {
          syncData.map(item => {
            if (progress === item.offset) {
              setSingleFile(item)
              setPlayedIcon(true)
              // console.log('翻页的数据为：', item)
            }
          })
          return EMPTY;
        })
      ).subscribe()
  }

  // 根据当前回放播放进度渲染文件演示记录
  useEffect(() => {
    const sub = filePlayEffect(isPlaying, fileSynData)
    return () => sub.unsubscribe();
  }, [isPlaying, fileSynData])


  // 视频播放是否结束
  useEffect(() => {
    if (ui_videoEnded) {
      setPlayedIcon(false)
      setPlayedShow(false)
    }
  }, [isPlaying, ui_videoEnded])

  return (
    //下面按情况显示封面图片
    <View onClick={closeAllPop} className={((roomStatus === ROOM_STATUS.NOT_STARTED || type === LIVE_TYPE.AUDIO) && (roomRole !== ROOM_ROLE.OWNER_ANCHOR || roomRole !== ROOM_ROLE.ANCHOR)) || roomStatus === ROOM_STATUS.PAUSED || (!isPlaying && roomStatus === ROOM_STATUS.ENDED) ? 'operator-layer' : 'operator-nolayer'}>
      {isclickMouse == false && (
        <View id='navBar' style={{ height: navBarHeight + 'px', width: (screenWidth - navWidth) + 'px', top: isHorizontal ? "0" : `${statusBarHeight}px` }}>
          <View className='navBarTitle' >
            {/* 头像/观看人数 */}
            <Image className='goback' src='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/goback.png' onClick={goBack}></Image>
            <Image className='gohome' src='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/home.png' onClick={goHome}></Image>
            <View className={roomRole === ROOM_ROLE.AUDIENCE ? 'borderBox' : 'borderBox1'} >
              <View className='borderLeft' onClick={goInformationPage}>
                <View className='tx' >
                  <Image src={anchorId ? anchorLogo : ownerLogo} className='tx_img'></Image>
                </View>
                <View className='information' onClick={goInformationPage}>
                  <View className='ownName'>{anchorId ? anchorName : ownerName}</View>
                  <View className='frequency'>{numFormat(visits)}人观看</View>
                </View>
              </View>
              {
                roomRole === ROOM_ROLE.AUDIENCE && (
                  <View className='follow' onClick={isClickAttention}>{isAttention ? '已关注' : '关注'}</View>
                )
              }
            </View>
            <View className='shareItem' onClick={clickOpenShare}>
              <Image src='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/list.png' className='list_img'></Image>
              <View className='share'>分享榜</View>
            </View>
            <View className='updown' onClick={handleClick} >
              <Image className=' updown-img' src={isOpenTop ? 'https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/Button.png' : 'https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/Button.png'} ></Image>
            </View>
          </View>
        </View>
      )}

      {/* 语音直播时显示头像 */}
      {type === LIVE_TYPE.AUDIO && roomStatus === ROOM_STATUS.STARTED && (
        <View className='type-audio'>
          <Image src={anchorId ? anchorLogo : ownerLogo} className='type-audio-img'></Image>
          <View className='type-audio-name'>{anchorId ? anchorName : ownerName}</View>
          {audioStatus && <Image src={ASSETS_PATH + '/AudionLive.png'} className='type-audio-icon'></Image>}
        </View>
      )}

      {/* 直播间详情信息 */}
      <View className='liveMsg' style={{ display: isOpenTop == true ? "block" : "none" }}>
        <View className='closeIcon'><Image src='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/closeIcon.png' className='close_img'></Image></View>
        <View className='title1'><Text>{roomName}</Text></View>
        <View className='content'>
          <View className='ct-left'>
            <View className='name'> 主持人 </View>
            {/* <View className='addName'> 机构名称 </View> */}
          </View>
          <View className='ct-right'>
            <View className='owner'> {anchorName || ownerName} </View>
            {/* <View className='org'>
              <View className='orgName'> {orgName || '暂无'} </View>
              <View className='orgStatus'>{orgName ? "已认证" : "未认证"}</View>
            </View> */}
          </View>
        </View>
        <View className='tip'> 简介</View>
        <View className='tip_ct'> {description || '暂无'} </View>
      </View>
      {/* 直播设置/机构信息入口 */}
      {isclickMouse == false && (
        <View id='countBlock' style={{ display: isOpenTop == true ? "none" : "block" }}>
          {
            orgId && (
              <View className='number' onClick={goOrgInfoPage}>
                <Image src='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/orgIcon.png' className='num_img'></Image>
                <View className='num'>{orgName}</View>
              </View>
            )
          }

          {
            (roomRole === ROOM_ROLE.OWNER_ANCHOR || roomRole === ROOM_ROLE.ANCHOR || roomRole === ROOM_ROLE.OWNER_ASSISTANT || roomRole === ROOM_ROLE.ASSISTANT) && (
              <View className='set' onClick={setting}>
                <Image src='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/set.png' className='set_img'></Image>
              </View>
            )
          }
        </View>
      )}

      {
        (roomRole === ROOM_ROLE.OWNER_ANCHOR || roomRole === ROOM_ROLE.ANCHOR) && (roomStatus === ROOM_STATUS.STARTED || roomStatus === ROOM_STATUS.PAUSED) && (
          <View className='startTime' onClick={setEndShow} style={{ display: isOpenTop == true ? "none" : "block" }}>
            <View className='start'>
              <Image src='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/start.png' className='stop_img'></Image>
              <View className='allTime'>{timeData}</View>
            </View>
          </View>
        )
      }
      {
        roomStatus === ROOM_STATUS.ENDED && isclick && (
          <View className='showButton' onClick={clickShow}>
            <View className='show'><Image src={isclickMouse ? 'https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/hide.png' : 'https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/show.png'} className='show_img'></Image></View>
            <View className='showText' >{isclickMouse ? '显示按钮' : '隐藏按钮'}</View>
          </View>
        )
      }

      {/* 观众端文件演示中图标 */}
      {
        roomRole === ROOM_ROLE.AUDIENCE && showFiles && (
          <View className={isHorizontal ? 'playing2' : 'playing'} onClick={clickWatch}>
            <View className='play'>
              <Image src='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/Playing.png' className='playing_img'></Image>
              <View className='running'>文件演示中</View>
            </View>
          </View>
        )
      }
      {/* 直播间背景图 */}
      {
        ((roomStatus === ROOM_STATUS.NOT_STARTED || roomStatus === ROOM_STATUS.PAUSED || roomStatus === ROOM_STATUS.RESUME) && roomRole !== ROOM_ROLE.OWNER_ANCHOR && roomRole !== ROOM_ROLE.ANCHOR) || (!isPlaying && roomStatus === ROOM_STATUS.ENDED) && (
          <View className='background'>
            {ChannelSytle.appName === '直盐' &&
              (<Image src='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/logo.png' className='logoImg'></Image>)
            }
          </View>
        )
      }
      {/* 中间区域 */}
      {
        roomStatus !== ROOM_STATUS.STARTED && !isPlaying && (
          <View id='centerBlock'>
            <View className='center-top'>
              <View className='tip'>
                {(roomStatus === ROOM_STATUS.NOT_STARTED && type === LIVE_TYPE.VIDEO)
                  ? '直播未开始' : (roomStatus === ROOM_STATUS.NOT_STARTED && type === LIVE_TYPE.AUDIO)
                    ? '语音直播未开始' : roomStatus === ROOM_STATUS.ENDED
                      ? '直播已结束' : '直播暂停中'}
              </View>
              <View className='time'>{roomStatus === ROOM_STATUS.NOT_STARTED ? formatTime(startTime) + ' 开始' : '直播时长: ' + timeData}</View>
            </View>
            {(roomRole === ROOM_ROLE.OWNER_ANCHOR || roomRole === ROOM_ROLE.ANCHOR) && (roomStatus === ROOM_STATUS.NOT_STARTED || roomStatus === ROOM_STATUS.PAUSED || roomStatus === ROOM_STATUS.RESUME) && (
              <View >
                <Button className='begin' onClick={setShow} > {roomStatus === ROOM_STATUS.NOT_STARTED ? '开始直播' : '继续直播'} </Button>
              </View>
            )}
            {(roomStatus === ROOM_STATUS.ENDED) && (
              <View >
                <Button className='begin' onClick={playBack} >观看回放</Button>
              </View>
            )}
          </View>
        )
      }

      {/* 倒计时 */}
      {
        timeShow && (
          <View className='timeModel'>
            <View className='biginTime' >{timeValue}</View>
          </View>
        )
      }

      {isclickMouse == false && (
        <View id='msgBlock'  >
          <ScrollView scrollY scrollWithAnimation scrollIntoView={toview} className='contentMsg' enhanced onDragging={disableAutoScroll} onClick={toChat} onScrollToLower={enableAutoScroll}>
            {
              // 聊天信息展示区域
              msgList.length > 0 && msgList.map((msg, index) =>
                <View key={String(index)} className='msgBox'>
                  <View className='msg-column-item' id={'msg' + index}>
                    <Label style={{ color: msg.nick === 'administator' ? 'red' : 'white' }} className='nick'>{msg.nick || "游客"}: </Label>
                    <Label className='msgText'>{!msg.isRevoked ? msg.payload.text : "消息已被撤回."}</Label>
                  </View>
                </View>
              )
            }
          </ScrollView>
          <View className='bottom'>
            <View className='input' onClick={hideInput}>这里发言..</View>
          </View>
        </View>
      )}

      {/* 新消息提示 */}
      {
        hasNewMsg && (
          <View className='newMsg' onClick={enableAutoScroll}>
            <Image src='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/lower.svg' className='updown'></Image>
            <View className='newText'>有新消息</View>
          </View>
        )
      }
      {/* 键盘输入框 */}
      {
        showInput && (
          <View className='inputMsg' style={{ 'bottom': keyboardHeight }}>
            <View className='input-box'>
              <Textarea className='input-text'
                maxlength={80}
                cursorSpacing={90}
                fixed
                value={inputVal}
                onInput={getInputVal}
                showConfirmBar={false}
                adjustPosition={false}
                placeholder='发一条友善的评论吧...'
                confirm-type='send'
                onConfirm={sendRoomMsg}
                onBlur={hideInput}
                onFocus={getKeyboardHeight}
                autoFocus
                onKeyboardHeightChange={onKeyboardheightchange}
              />
            </View>
            <View className='send-bnt' onClick={sendRoomMsg}>发送</View>
          </View>
        )
      }

      {isclickMouse == false && (
        <View id='likeBlock'>
          <View className='right'>
            {/* 文件上传按钮 */}
            <Image src={ASSETS_PATH + '/live_Text.png'} className='config_img' onClick={openFileMenu}></Image>
            {
              //签到按钮
              hasSignIn && (
                <Image src={ASSETS_PATH + '/live_SignIn.png'} className='sign_img' onClick={signIn}></Image>
              )}
            {
              //转发按钮
              (allowShare || roomRole === ROOM_ROLE.OWNER_ANCHOR || roomRole === ROOM_ROLE.ANCHOR) && (
                <Image src={ASSETS_PATH + '/live_Share.png'} className='share_img' onClick={shareRoom}></Image>
              )}
            {/* 点赞按钮 */}
            <View className='ider'>
              <Image src={like ? 'https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/active.gif' : ASSETS_PATH + '/live_Likes.png'} className='ider_img' onClick={clickLike} ></Image>
              <View className='inputBox'>
                <View className='shuzi'>{numFormat(likes)}</View>
              </View>
            </View>
          </View>
        </View>
      )}


      {/* 竖屏底部弹窗  */}
      <AtFloatLayout title='直播设置' isOpened={openSetting && (roomRole === ROOM_ROLE.OWNER_ANCHOR || roomRole === ROOM_ROLE.ANCHOR || roomRole === ROOM_ROLE.ASSISTANT || roomRole === ROOM_ROLE.OWNER_ASSISTANT) && isHorizontal == false} onClose={() => setOpenSetting(false)} className='bottom-set' >
        <View className='bt-title'>互动操作</View>
        <AtGrid hasBorder={false} columnNum={4} className='box2' onClick={interaction} data={(roomStatus === ROOM_STATUS.STARTED || roomStatus === ROOM_STATUS.PAUSED && (type !== LIVE_TYPE.OBS && type !== LIVE_TYPE.OBS_REC && type !== LIVE_TYPE.VR)) ?
          [{
            image: 'https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/mic_2.png',
            value: '邀请连麦'
          }, {
            image: 'https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/cut.png',
            value: '镜头切换',
          }]
          :
          [{
            image: 'https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/cut.png',
            value: '镜头切换',
          }]

        }
        />
        <View className='bt-title'>直播设置</View>
        {/* 直播未开始的设置 */}
        {
          roomStatus === ROOM_STATUS.NOT_STARTED && (
            <AtGrid hasBorder={false} columnNum={4} className='box2' onClick={toTeam} data={[...AtGridData].filter(({ value }, index, array) => value !== "暂停直播")} />
          )
        }
        {/* 直播中的设置 */}
        {
          (roomStatus === ROOM_STATUS.STARTED || roomStatus === ROOM_STATUS.PAUSED) && (
            <AtGrid hasBorder={false} columnNum={4} className='box2' onClick={toTeam} data={[...AtGridData].filter(({ value }, index, array) => value !== "编辑房间")} />
          )
        }
        {/* 直播结束后的设置 */}
        {
          roomStatus === ROOM_STATUS.ENDED && (
            <AtGrid hasBorder={false} columnNum={4} className='box2' onClick={toTeam} data={[...AtGridData].filter(({ value }, index, array) => value === "允许分享" || value === '密码设置' || value === '评论设置')} />
          )
        }
      </AtFloatLayout >


      {/* 横屏设置弹窗 */}
      {
        isHorizontal && openSetting && (
          <View className='settingModel'>
            <View className='topBox' style={{ height: navHeight + 'px', top: topPadding + 'px' }}>
              <View className='contentBox'>
                <Image className='none' src='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/goback.png' onClick={() => setOpenSetting(false)}></Image>
              </View>
            </View>
            <View className='bottomBox' style={{ top: (topPadding + navHeight) + 'px' }}>
              <View className='topTitle'>直播设置</View>
              <View className='itemBox'>
                <View className='item' onClick={switchCamera}>
                  <Image className='itemImg' src='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/cut.png' />
                  <View className='itemTitle'>镜头切换</View>
                </View>
                {/* 直播未开始的设置 */}
                {
                  roomStatus === ROOM_STATUS.NOT_STARTED && dataArr.map((item, index) => (
                    <View className='item' key={index} onClick={() => toTeam(item, index)}>
                      <Image className='itemImg' src={item.image} />
                      <View className='itemTitle'>{item.value}</View>
                    </View>
                  )
                  )
                }

                {/* 直播开始中的设置 */}
                {
                  (roomStatus === ROOM_STATUS.STARTED || roomStatus === ROOM_STATUS.PAUSED) && data1Arr.map((item, index) => (
                    <View className='item' key={index} onClick={() => toTeam(item, index)}>
                      <Image className='itemImg' src={item.image} />
                      <View className='itemTitle'>{item.value}</View>
                    </View>
                  )
                  )
                }

                {/* 直播结束后的设置 */}
                {
                  roomStatus === ROOM_STATUS.ENDED && data2Arr.map((item, index) => (
                    <View className='item' key={index} onClick={() => toTeam(item, index)}>
                      <Image className='itemImg' src={item.image} />
                      <View className='itemTitle'>{item.value}</View>
                    </View>
                  )
                  )
                }
              </View>
            </View>
          </View>
        )
      }

      {/* 主播邀请连麦 */}
      <AtFloatLayout isOpened={isInvite && isHorizontal === false} className='inviteContent' onScrollToLower={refreshAudienceList}>
        <View onClick={inviteModel}>
          <View className='invite-title'>
            <Image src='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/goBack.png' className='invite-title-img' onClick={goBackSetting}></Image>
            <View className='invite-title-name'>邀请连线</View>
          </View>
          <View className='invite-search'>
            <Input type='text' className='invite-ipt' placeholder='请输入昵称' onInput={updateSearchInvite}></Input>
            <Button className='invite-search-btn' onClick={searchInvite}>搜索</Button>
          </View>
          <View className='invite-list'>
            <ScrollView scrollY scrollWithAnimation className='invite-list-scroll' enhanced >
              {!!audienceList && audienceList.length > 0 && audienceList.map((item, index) => (
                <View className='invite-list-item' key={String(index)}>
                  <View className='invite-list-item-img'><Image src={item.avatar}></Image></View>
                  <View className='invite-list-item-content'>
                    <View className='item-content-name'>{item.nickName}</View>
                    {/* <View className="item-content-phone"> 手机号: {item.nickPhone}</View> */}
                  </View>
                  <View className={item.inviteStatus === INVITE_STATUS.ACCEPT ? 'invite-list-item-status disable' : 'invite-list-item-status'} onClick={() => hanldeConnect(item.userId, index)}>
                    {(item.inviteStatus === INVITE_STATUS.ACCEPT || item.inviteStatus === INVITE_STATUS.CONNECTING) ? '连线中..' : '邀请连线'}
                    {/* 邀请连线 */}

                  </View>
                </View>
              ))}

            </ScrollView>
            {
              !!audienceList && audienceList.length == 0 && (
                <View style='width: 100%; color: #ddd; text-align: center; margin: 30px auto;'>
                  暂无可连线主播
                </View>
              )
            }
          </View>
        </View >
      </AtFloatLayout >

      {/* 主播身份上传文件 竖屏*/}
      <AtFloatLayout isOpened={isOpenFile && isHorizontal === false} className='setFile' >
        <View className='down'> <Image src='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/down1.png' className='down-img' onClick={() => setOpenFile(false)}></Image></View>
        {
          files.length > 0 && files.map((item, index) =>
            <View className='content' key={String(index)}>
              <View className='file'> <Image src={ASSETS_PATH + '/live_Upload.png'} className='file-img'></Image></View>
              <View className='flieName' onClick={() => openFile(item.fileUrl)}> {item.fileName}</View>
              {
                (roomRole === ROOM_ROLE.OWNER_ANCHOR || roomRole === ROOM_ROLE.ANCHOR) && roomStatus !== ROOM_STATUS.ENDED && (
                  <Button className='upload' onClick={() => fileTransCode(item.id, item.fileUrl, index)} style={{ background: (isSucceed && index === filesIndex) ? '#9a9a9a' : MAIN_COLOR }}>{(isSucceed && index === filesIndex) ? '文件转码中' : '演示文件'}</Button>
                )
              }
              {
                (roomRole === ROOM_ROLE.OWNER_ANCHOR || roomRole === ROOM_ROLE.ANCHOR) && (
                  <Button className='delete' onClick={() => cancelDeteleFiles(index)}>删除文件</Button>
                )
              }

              {
                roomRole === ROOM_ROLE.AUDIENCE && (
                  <Button className='upload' onClick={() => openFile(item.fileUrl)} >查看文件</Button>
                )
              }
            </View>
          )
        }
        {
          (roomRole === ROOM_ROLE.OWNER_ANCHOR || roomRole === ROOM_ROLE.ANCHOR) && (
            <Button className='uploadFile' onClick={clickUploadFile} style={{ display: files.length === 5 ? "none" : "block" }}>上传文件({files.length}/5)</Button>
          )
        }
      </AtFloatLayout >

      {/* 上传文件 横屏 */}
      {
        isHorizontal && isOpenFile && (
          <View className='settingFiles'>
            <View className='iconBox' style={{ height: navHeight + 'px', top: topPadding + 'px' }}>
              <View className='headBox'>
                <Image className='none' src='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/closeIcon.png' onClick={() => setOpenFile(false)}></Image>
              </View>
            </View>
            <View className='filesBox' style={{ top: (topPadding + navHeight) + 'px' }}>
              <ScrollView scrollY className='scroll' style={{ height: (screenHeight - (topPadding + navHeight)) + 'px' }}>
                {
                  files.length > 0 && files.map((item, index) =>
                    <View className='box1' key={String(index)}>
                      <View className='content' >
                        <View className='fileIcon'> <Image src='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/fileImg.png' className='file-img'></Image></View>
                        <View className='fliesName' onClick={() => openFile(item.fileUrl)}> {item.fileName}</View>
                      </View>
                      <View className='but' >
                        {
                          (roomRole === ROOM_ROLE.OWNER_ANCHOR || roomRole === ROOM_ROLE.ANCHOR) && roomStatus !== ROOM_STATUS.ENDED && (
                            <Button className='uploading' onClick={() => fileTransCode(item.id, item.fileUrl, index)} style={{ background: (isSucceed && index === filesIndex) ? '#9a9a9a' : 'linear-gradient(140deg, #ed3333 0%, #d20202 100%)' }}>{(isSucceed && index === filesIndex) ? '文件转码中' : '演示文件'}</Button>
                          )
                        }
                        {
                          (roomRole === ROOM_ROLE.OWNER_ANCHOR || roomRole === ROOM_ROLE.ANCHOR) && (
                            <Button className='deleted' onClick={() => cancelDeteleFiles(index)}>删除文件</Button>
                          )
                        }
                        {
                          roomRole === ROOM_ROLE.AUDIENCE && (
                            <Button className='uploading' onClick={() => openFile(item.fileUrl)} >查看文件</Button>
                          )
                        }
                      </View>
                    </View>
                  )}

                {
                  (roomRole === ROOM_ROLE.OWNER_ANCHOR || roomRole === ROOM_ROLE.ANCHOR) && (
                    <Button className='uploadFile' onClick={clickUploadFile} style={{ display: files.length === 5 ? "none" : "block" }}>上传文件({files.length}/5)</Button>
                  )
                }
              </ScrollView>
            </View>
          </View >
        )
      }

      {/* 分享榜单弹窗 */}
      {
        openShare && (
          <View className='shareBox'>
            <View className='shareList'>
              <View className='shareTitle'>
                <Text className='text'>分享榜</Text>
                <View className='closeButton' onClick={() => setOpenShare(false)}><Image src='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/close.png' className='close_img'></Image></View>
              </View>
              <ScrollView scrollY className='shareCenter'>
                {
                  shareData.length <= 9 && shareData.map((item, index) => (
                    <View className='shareContent' key={String(index)}>
                      <View className='shareContent-left'>
                        <View className='ranking'>{index + 1}</View>
                        <View className='UserAvatar'>
                          <Image src={item.avatar} className='avatar_img'></Image>
                        </View>
                        <View className='useName'>{item.nickName}</View>
                      </View>
                      <View className='shareContent-right'>
                        <View className='shareTimes'>分享次数</View>
                        <View className='shareNum'>{item.counts}</View>
                      </View>
                    </View>
                  )
                  )}
              </ScrollView>
              {
                shareData.map((item, index) => {
                  if (userId === item.userId) {
                    return (
                      <View className='ownShare' key={index}>
                        <View className='ownShare-left'>
                          <View className='UserAva'>
                            <Image src={item.avatar} className='avatar_img'></Image>
                          </View>
                          <View className='useNames'>我的邀请人数 {item.counts}</View>
                        </View>
                        <View className='ownShare-right'> 去分享</View>
                      </View>
                    )
                  }
                }
                )}
            </View>
          </View>
        )
      }

      {/* 主播端文件演示区域 */}
      {
        showFiles && (roomRole === ROOM_ROLE.OWNER_ANCHOR || roomRole === ROOM_ROLE.ANCHOR) && (
          <View className={isHorizontal ? 'fileBox1' : 'fileBox'}>
            <View className='fileHead' onClick={back}>
              <View className='fileTop' >
                <Image className='back' src='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/goback.png'></Image>
                <View className='return'>返回</View>
              </View>
            </View>
            <Swiper className='test-h' current={currentValue} circular onChange={SelectOptions} >
              {
                filesArry.map((item, index) => (
                  <SwiperItem className='swiperItem' key={index}>
                    <View className='Images'><Image className='areaImg' src={item.transcodeImgUrl} ></Image>
                      <View className='pages'>{currentValue + 1}/{item.pages}</View>
                    </View>
                  </SwiperItem>
                ))
              }
            </Swiper>
            <View className='fileBttom'>
              <View className='fileBt'>
                <View className='btLeft' onClick={() => clickPrev(filesIndex)}>上一页</View>
                <View className='btRight' onClick={() => clickNext(filesIndex)} >下一页</View>
              </View>
            </View>
          </View>
        )
      }

      {/* 观众端文件演示 */}
      {
        isWatch && roomRole === ROOM_ROLE.AUDIENCE && (
          <View className={isHorizontal ? 'synBox1' : 'synBox'}>
            <View className='topfileBox'>
              <View className='fileTop' onClick={toBack}>
                <Image className='back' src='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/goback.png'></Image>
                <View className='return'>返回</View>
              </View>
            </View>
            <View className='area'>
              <View className='Images'><Image className='areaImg' src={fileSynUrl} ></Image></View>
              <View className='pages'>{filePage}/{totalPages}</View>
            </View>
          </View>
        )
      }

      {/* 观看回放文件演示 */}
      {
        playedShow && singleFile && (
          <View className='synEnded' >
            <View className='area'>
              <View className='Images'><Image className='areaImg' src={singleFile.transcodeUrl + singleFile.page + '.jpg'} ></Image></View>
              <View className='pages'>{singleFile.page}/{singleFile.pages}</View>
            </View>
          </View>
        )
      }

      {/* 观众端文件演示中图标 */}
      {
        playedIcon && isclickMouse == false && (
          <View className={isHorizontal ? 'playing3' : 'playing1'} onClick={clickPlayed}>
            <View className='play'>
              <Image src='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/Playing.png' className='playing_img'></Image>
              <View className='running'>文件演示中</View>
            </View>
          </View>
        )
      }

      {/*开始直播提示框  */}
      {

        showModel && (type !== LIVE_TYPE.OBS_REC) && (
          <View className='modelBox'>
            <View className='tipsBox'>
              <View className='tipsContent'>确认开始直播吗？</View>
              <View className='tipsButton'>
                <View className='cancelText' onClick={() => setShowModel(false)}>取消</View>
                <View className='confirmText ' onClick={daojishi}>确认</View>
              </View>
            </View>
          </View>
        )
      }

      {/*结束直播提示框  */}
      {
        endLive && (
          <View className='modelBox'>
            <View className='tipsBox'>
              <View className='tipsContent'>确认结束该直播吗？</View>
              <View className='tipsButton'>
                <View className='cancelText' onClick={() => setEndLive(false)}>取消</View>
                <View className='confirmText ' onClick={endPush}>确认</View>
              </View>
            </View>
          </View>
        )
      }

      {/*删除文件提示框  */}
      {
        showDetele && (
          <View className='modelBox'>
            <View className='tipsBox'>
              <View className='tipsContent'>确认删除该文件吗？</View>
              <View className='tipsButton'>
                <View className='cancelText' onClick={cancelDeteleFiles}>取消</View>
                <View className='confirmText ' onClick={() => deleteFile(filesIndex)}>确认</View>
              </View>
            </View>
          </View>
        )
      }

      <Login goUrl={goUrl} setGoUrl={setGoUrl} clicked={clicked} setClicked={setClicked} />
    </View >
  )
}
export default React.memo(Index)



